#include "Master.h"

Master::Master(void)
{
	stations['T'] = new Terminal();
	stations['R'] = new RailwayStation();
	stations['S'] = new Harbor();
	stations['A'] = new Airport();
}

Master::~Master(void)
{
}

void Master::ReadFile()
{
	ifstream in;
 	in.open(INPUT_FILENAME );
 	
 	char code;

//	in >> code;
 	while( !in.eof() ) {
		in >> code;
 		if (isInputOrder(code))
 			orderInput(in);
		else
			transportInput(in , code);
 	}
	in.close();
}

void Master::Process()
{
	map<char,Station*>::iterator stationIter = stations.begin();
	for (; stationIter != stations.end() ; ++ stationIter )	{
		(stationIter->second)->Process();
	}
}

void Master::PrintResult()
{
	printStation();
	printTransport();
	Logger::getInstance()->printAllLog();
}

bool Master::isInputOrder( char code)
{
	return code == 'O';
}

void Master::orderInput( ifstream &in )
{
	char transport;
	int OccurTime;
	int load;
	in >> transport >> OccurTime >> load;

	stations[transport]->pushOrder(Order(OccurTime , load));
}

void Master::transportInput( ifstream & in , char code )
{
	string id;
	int arrivalTime;
	int maxLoad;
	int currentLoad;
	int offLoad;
	
	in >> id >> arrivalTime >> maxLoad >> currentLoad >> offLoad;

	Transport* transport = stations[code]->pushTransport(
		Transport(id , arrivalTime , maxLoad , currentLoad , offLoad));
	transports.push_back(transport);
}

void Master::Release()
{
	stations.clear();
}

void Master::printStation()
{
	ofstream out;
	out.open(STATIONS_OUTPUT_FILENAME);

	IPrint* print[4] = { stations['T'] , stations['R'] , stations['S'] , stations['A']} ;
	for (int i=0;i<4;i++)
		print[i]->printResult(out);
	out.close();
}

void Master::printTransport()
{
	ofstream out;
	out.open(TRANSPORTS_OUTPUT_FILENAME);
	vector<Transport*>::iterator transport = transports.begin();
	IPrint* print;
	do 
	{
		print = (*transport);
		print->printResult(out);
		++transport;
	} while (transport != transports.end());

	out.close();
}
